<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\PaginateRequest;
use App\Http\Requests\User\UserStoreRequest;
use App\Http\Requests\User\UserUpdateRequest;
use App\Models\Auth\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function index(PaginateRequest $request) {
        $searchText = $request->input('searchText');
        $result = User::with('roles');

        if (!!$searchText) {
            $fields = ['title', 'description'];
            User::buildWhereClause($result, $fields, $searchText);
        }

        return response()->json(User::pagination($result, $request));
    }

    public function show(User $user) {
        return response()->json($user->load('roles'));
    }

    public function store(UserStoreRequest $request) {
        $user = User::create($request->input('user'));
        if ($request->has('user.password')) $user->updatePassword($request->input('user.password'));

        $roles = $request->input('roles', []);
        $user->roles()->sync($roles);

        return response()->json($user->load('roles'));
    }

    public function update(UserUpdateRequest $request, User $user) {
        $user->update($request->input('user'));
        if ($request->has('user.password')) $user->updatePassword($request->input('user.password'));

        $roles = $request->input('roles', []);
        $user->roles()->sync($roles);

        return response()->json($user->load('roles'));
    }

    public function destroy(User $user) {
        return response()->json($user->delete());
    }

    public function logoutAllUser() {
        User::all()->each(function (User $user) {
            $user->accessTokens()->delete();
        });
        return response()->json(true);
    }

    public function logoutUser(User $user) {
        $user->accessTokens()->delete();
        return response()->json(true);
    }
}
